import { formatDate, urlToFileWithFormData } from "@/units/index.js";

export async function fetchBitcoinMagazineContent() {
    try {
        const response = await fetch('https://bitcoinmagazine.com/');
        if (!response.ok) {
            throw new Error('网络响应不是 OK');
        }
        const htmlContent = await response.text();
        console.log("获取到的页面内容:", htmlContent);

        // 这里可以进一步处理获取到的 HTML 内容，例如解析或提取特定信息
    } catch (error) {
        console.error("获取内容时出错:", error);
    }
}

export function bitcoinmagazineArticle() {
    // 获取图片信息
    const imageInfor = document.querySelector('.tdb_single_featured_image > .tdb-block-inner > a')
    console.log(imageInfor, imageInfor.src, 'qqqqqqqqqqqqq');
    if (!imageInfor) {
        console.log('未找到#NzQ2OjM3-1元素');
        return
    }
    const imageSrc = imageInfor.src || imageInfor.href
    const titleInfo = document.querySelector('.tdb-title-text').innerHTML
    console.log(titleInfo, 'titleeeeeeee');
    const authorInfo = document.querySelector('.tdb-author-name-wrap > .tdb-author-name').innerHTML
    console.log(authorInfo, 'author');
    const timeInfo = formatDate(document.querySelector('.tdb_single_date > .tdb-block-inner > .td-module-date').innerHTML)
    console.log(timeInfo, 'timetime');

    const mainContentItem = document.querySelectorAll('.tagdiv-type > .tdb-block-inner > p')
    console.log(mainContentItem, 'maincontent');
    let maincontent = ''
    mainContentItem.forEach(item => {
        maincontent += item.outerHTML
    })
    console.log(maincontent, 'maincontent');

    console.log(window.location.origin, 'window.location.origin');

    urlToFileWithFormData(imageSrc, 'asset.png').then(formData => {
        const file = formData.get('file');
        file.arrayBuffer().then(buffer => {
            chrome.runtime.sendMessage({
                type: "proxy",
                method: "POST",
                url: "/dex/upload",
                fileName: file.name,
                fileType: file.type,
                fileBuffer: Array.from(new Uint8Array(buffer))
            }, (response) => {
                let imgElement = `<img fetchpriority="high" src="${response.data}" width="696" height="522" sizes="(max-width: 696px) 100vw, 696px" alt="${titleInfo}" decoding="async" nitro-lazy-empty="" id="NzQyOjM3-1">`
                console.log(response, '图片文件数据数据');
                const params = {
                    author: authorInfo,
                    category: '1',
                    content: imgElement + maincontent,
                    cover: response.data,
                    publishDate: timeInfo,
                    source: 'https://bitcoinmagazine.com',
                    status: 0,
                    title: titleInfo,
                    type: '1'
                }
                // 获取token并请求保存接口
                chrome.storage.local.get('token', (data) => {
                    const token = data.token;
                    chrome.runtime.sendMessage({
                        type: "proxy",
                        method: "POST",
                        url: "/dex/dex/news/save",
                        body: params,
                        token: token
                    }, (saveResponse) => {
                        console.log(saveResponse, '新闻保存结果');
                    });
                });
            });
        });
    }).catch(error => {
        console.error('上传图片失败:', error);
    });
}